﻿@using Microsoft.AspNetCore.Components

@inject AppState appState
@inject NavigationManager navigationManager
@implements IDisposable
@inject AuthenticationStateProvider authStateProvider
@inject IStringLocalizer<Global> L

    <ul class="breadcrumb">
        <li>
            <a href="/">@RootLinkTitle</a>
        </li>
        @foreach (var path in paths.Select((value, i) => (value, i)))
        {
            if (paths.Count() > 1)
            {
                if (path.i == 0)
                {
                    <li><a href="@(baseUrl + path.value)">@L["BreadCrumb" + path.value].ToString().ToUpper()</a></li>
                }
                else if (path.i == paths.Count() - 1)
                {
                    <li>@L["BreadCrumb" + String.Join("", paths)].ToString().ToUpper()</li>
                }
                else
                {
                    <li><a href="@(baseUrl + String.Join("/",paths,0, path.i+1))">@L["BreadCrumb" + String.Join("", paths, 0, path.i+1)].ToString().ToUpper()</a></li>
                }
            }
            else
            {
                <li>@L["BreadCrumb" + path.value].ToString().ToUpper()</li>
            }
        }
    </ul>

@code {
    // This is just for demo and is VERY Hackish  for several reasons
    // Blazor does not have page implemented for client side... as far as I know so we split page names with underscore for now.
    // Path system is hack as well as the Url.. Maybe you have a better solution?

    public bool IsLoggedIn = false;

    [Parameter]
    public string RootLinkTitle { get; set; }

    [CascadingParameter]
    Task<AuthenticationState> authenticationStateTask { get; set; }

    public string[] paths;
    public string baseUrl;

    protected override async Task OnParametersSetAsync()
    {
        IsLoggedIn = false;
        var user = (await authenticationStateTask).User;

        if (user.Identity.IsAuthenticated)
        {
            IsLoggedIn = true;
        }
    }

    protected override async Task OnInitializedAsync()
    {
        baseUrl = navigationManager.BaseUri;
        await BuildBreadcrumbsAsync();
        navigationManager.LocationChanged += OnLocationChanges;
        await base.OnInitializedAsync();
    }

    void OnLocationChanges(object sender, LocationChangedEventArgs e) => BuildBreadcrumbsAsync();

    private async Task BuildBreadcrumbsAsync()
    {
        string uri = navigationManager.Uri.Split('?')[0].Replace(baseUrl, "/").Trim();

        if (IsLoggedIn)
        {
            await appState.SaveLastVisitedUri(uri);
        }

        paths = String.IsNullOrEmpty(uri) ? new string[] { } : uri.Split('/');
        StateHasChanged();
    }

    public void Dispose()
    {
        navigationManager.LocationChanged -= OnLocationChanges;
    }
}
